package com.xiaoyung.easyisapisdk.common.util;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.ObjectUtils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

/**
 * 说明：参数封装Map
 */
public class PageData extends LinkedHashMap<String, Object> implements Serializable {
	// extends LinkedHashMap<String,Object>
	private static final long serialVersionUID = 1L;

	// Map map = null;
	// HttpServletRequest request;

	public final static String multipart_parameter_map = "multipart_parameter_map";
	public static String _requset_body_data = "_requset_body_data";// 页面请求 body 中的传入的参数

	public PageData() {
		// map = new LinkedHashMap();
		// 自己new出来的也加上 service层不要和session打交道
		// put(Const.TENANT_ID,SessionUtils.getTENANT_ID());//每个pd必须得有这个,否则报错
	}
	
	@SuppressWarnings("unchecked")
	public PageData(Object obj) {
		if(obj!=null) {
			if(obj instanceof Map) {
				putAll((Map<String,Object>)obj);
			}else {
				//javaBean
				JSONObject json= (JSONObject)(JSON.toJSON(obj));
				putAll(json);
			}
		}
	}
	
	public PageData(String key, Object value) {
		put(key, value);
	}

	/*	@Override
		public Object get(Object key) {
			Object obj = null;
			if(super.get(key) instanceof Object[]) {
				Object[] arr = (Object[])super.get(key);
				//干嘛要这样 ??  看日后会不户有地方报错
				//obj = request == null ? arr:(request.getParameter((String)key) == null ? arr:arr[0]);
				return arr;
			} else {
				obj =super.get(key);
			}
			return obj;
		}*/
	@Override
	public Object put(String key, Object value) {
		/*if(Character.isUpperCase(key.charAt(0))) {
			key=StringUtil.underlineToCamel(key);
		}*/
		/*if(("extData".equals(key)||"ext_data".equals(key)) && value instanceof JSONObject) {
			JSONObject json=(JSONObject)value;
			super.putAll(json);
		}*/
		return super.put(key, value);
	}

	@Override
	public Object get(Object key) {
		/*if(keyFormat==1) {
			key=StringUtil.camelToUnderline(key.toString());
		}else if(keyFormat==2) {
			key=StringUtil.underlineToCamel(key.toString());
		}*/

		Object value = super.get(key);
		String keyStr = key.toString();
		if (value == null) {
			String camelName = null;
			if (Character.isUpperCase(keyStr.charAt(0)) || keyStr.indexOf("_") > -1) {
				// 根据驼峰模式去拿
				camelName = StringUtils.underlineToCamel(keyStr);
				value = super.get(camelName);
			}

		}
		return value;
	}

	@SuppressWarnings("unchecked")
	public <T> T getObject(Object key) {
		Object v = get(key);
		return v == null ? null : (T) v;
	}

	public String getString(Object key, String defValue) {
		Object v = get(key);
		return ObjectUtils.isEmpty(v) ? defValue : v.toString().trim();
	}

	public String getString(Object key) {
		return getString(key, null);
	}

	public Boolean getBoolean(Object key) {
		return getBoolean(key, null);
	}

	public Boolean getBoolean(Object key, Boolean defValue) {
		Object v = get(key);
		if(ObjectUtils.isEmpty(v)) {
			return defValue;
		}else {
			if(v instanceof Boolean) {
				return (Boolean)v;
			}else {
				return (v.toString().equals("true") || v.toString().equals("1"));
			}
		}
	}

	public Integer getInteger(Object key, Integer defValue) {
		Object v = get(key);
		if (v == null || StringUtils.isEmpty(v.toString())) {
			return defValue;
		} /*else if(StringUtils.isEmpty(v.toString())) {
			return 0;//
			}*/else {
			return Integer.valueOf(v.toString());
		}
	}

	public Integer getInteger(Object key) {
		return getInteger(key, null);
	}
	
	
	public Date getDate(Object key, Date defValue) {
		Object v = get(key);
		if (v == null || StringUtils.isEmpty(v.toString())) {
			return defValue;
		} else {
			try {
				return DateUtils.parseDate(v);//支持多种格式
				// yyyy-MM-dd
				//return DateUtils.parseDate(v.toString(),DateUtils.YYYY_MM_DD);//.fomatDate(v.toString());
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
		}
	}

	public Date getDate(Object key) {
		return getDate(key, null);
	}

	public Double getDouble(Object key,Double defValue) {
		Object v=get(key);
		if(v==null||StringUtils.isEmpty(v.toString())) {
			return defValue;
		}else if(v instanceof Double){
			return (Double)v;
		}else {
			return Double.valueOf(v.toString());
		}
	}
	public Double getDouble(Object key) {
		return getDouble(key,null);
	}

	public BigDecimal getBigDecimal(Object key, BigDecimal defValue) {
		Object v = get(key);
		if (v == null || StringUtils.isEmpty(v.toString())) {
			return defValue;
		} else {
			Double db = getDouble(key);
			return BigDecimal.valueOf(db);
		}
	}

	public BigDecimal getBigDecimal(Object key) {
		return getBigDecimal(key, null);
	}

	public Long getLong(Object key, Long defValue) {
		Object v = get(key);
		String strValue = v == null ? null : v.toString();
		if (strValue != null && strValue.indexOf(".") > -1) {
			strValue = strValue.substring(0, strValue.indexOf("."));
		}
		Long longValue = (strValue == null || "".equals(strValue)) ? null : Long.valueOf(strValue);

		return longValue == null ? defValue : longValue;
	}

	public Long getLong(Object key) {
		return getLong(key, null);
	}

	public String[] getArr(Object key) {
		Object v=get(key);
		if(v!=null) {
			if(v instanceof String[]) {
				return (String[]) v;
			}else if(v instanceof JSONArray) {
				return ((JSONArray)v).stream().map(s -> s.toString()).toArray(String[]::new);
			}else {
				return v.toString().split(",");
			}
		}
		return null;
	}

	public static Object[] convertArrValue(Object objValue, String splitChar) {
		if (objValue != null) {
			Object[] valueArr = null;

			if (objValue instanceof String[]) {
				valueArr = (String[]) objValue;
			} else if (objValue instanceof Integer[]) {
				valueArr = (Integer[]) objValue;
			} else if (objValue instanceof Double[]) {
				valueArr = (Double[]) objValue;
			} else if (objValue instanceof BigDecimal[]) {
				valueArr = (BigDecimal[]) objValue;
			} else if (objValue instanceof Object[]) {
				valueArr = (Object[]) objValue;
			} else if (objValue instanceof String) {
				valueArr = objValue.toString().split(StringUtils.isEmpty(splitChar)?",":splitChar);
			} else if (objValue instanceof Collection) {
				valueArr = ((Collection<?>) objValue).toArray();
			} else {
				valueArr = new Object[] { objValue };
			}
			return valueArr;
		}
		return null;
	}
	
	public Object[] getObjArr(Object key) {
		return getObjArr(key, null);
	}
	public Object[] getObjArr(Object key,String splitChar) {
		Object value=get(key);
		return convertArrValue(value,splitChar);
	}
	public List<String> getList(Object key) {
		String[] arr = getArr(key);
		if (arr != null && arr.length > 0) {
			List<String> list = new ArrayList<>();
			for (int i = 0; i < arr.length; i++) {
				if (!StringUtils.isEmpty(arr[i])) {
					list.add(arr[i]);
				}
			}
			return list;
		}
		return null;
	}

	public Long[] getLongArr(String key) {
		String[] arr = getArr(key);
		if (arr != null && arr.length > 0) {
			Long[] longs = new Long[arr.length];
			for (int i = 0; i < arr.length; i++) {
				longs[i] = Long.valueOf(arr[i]);
			}
			return longs;
		} else {
			return null;
		}
	}


	public String getYesNoString(Object key) {
		// return "yes".equals((String)get(key))?"yes":"no";
		return getYesNoString(key, "yes", "no");
	}

	public String getYesNoString(Object key, String yes, String no) {
		return yes.equals(getString(key)) ? yes : no;
	}

	/**
	 * 
	 * @param pd           传入数据
	 * @param keys         第一个keys的值 若空则放弃
	 * @param requiredKeys 必须的值 若没有则放弃
	 * @return
	 */
	/*public String getRepatJson(String[] keys,String[] requiredKeys){
		return JSON.toJSONString( getRepatJsonList(keys,requiredKeys));
	}
	public List<PageData> getRepatJsonList(String[] keys,String[] requiredKeys){
		PageData pd=this;
		List<PageData> repeatJson=new ArrayList<>();
			int count=0;
			do{
				String num=(count==0?"":"-"+(count+1));
				String r=keys[0]+num;
				if(pd.containsKey(r) && StringUtils.isNotEmpty(pd.getString(r))){
					boolean flag=true;
					if(requiredKeys!=null){
						
						for (int j = 0; j < requiredKeys.length; j++) {
							if(StringUtils.isEmpty(pd.getString(requiredKeys[j]+num))){
								flag=false;
								break;
							}
						}
						
					}
					
					if(flag){
						PageData row=new PageData();
						for (int j = 0; j < keys.length; j++) {
							row.put(keys[j], pd.get(keys[j]+num));
						}
						repeatJson.add(row);
						
					}
				}
				count++;
			}while(count<pd.size());
	
		return repeatJson;
	}*/

	/*public void emptyInt2Zero(String ... args) {
		for (int i = 0; i < args.length; i++) {
			if(ObjectUtils.isEmpty(this.get(args[i]))){
				this.put(args[i], 0);
			}
		}
	}*/

	/**
	 * 将数据库大写字段 格式 转换成实体字段格式 TENANT_NAME 转换 tenantName 这样
	 */
	public PageData format2EntityKeyName() {
		PageData nPageData = new PageData();
		for (java.util.Map.Entry<String, Object> entry : this.entrySet()) {
			String oldKey = entry.getKey();
			String key = oldKey.toLowerCase();
			int index = -1;
			while ((index = key.indexOf("_")) > -1) {
				// _不是第一个也不是最后一个
				if (index != 0 && index != key.length() - 1) {
					String str = String.valueOf(key.charAt(index + 1)).toUpperCase();
					key = key.substring(0, index) + str + key.substring(index + 2, key.length());
				}
			}
			nPageData.put(key, entry.getValue());

		}
		return nPageData;
	}

	public static List<PageData> format2EntityKeyNameList(List<PageData> list) {
		return format2EntityKeyNameList(list, false);
	}

	public static List<PageData> format2EntityKeyNameList(List<PageData> list, boolean newList) {
		List<PageData> ret = new ArrayList<>();
		for (int i = 0; i < list.size(); i++) {
			if (newList) {
				ret.add(list.get(i).format2EntityKeyName());
			} else {
				list.set(i, list.get(i).format2EntityKeyName());
			}
		}
		return newList ? ret : list;
	}
	public JSONObject getJSONObject(String key) {
		Object json = get(key);
		if(json!=null ) {
			if(json instanceof JSONObject) {
				return (JSONObject)json;
			}else if(json instanceof String){
				 return (JSONObject)JSON.parseObject((String)json);
			}else {
				return (JSONObject)JSON.toJSON(json);
				//return JSON.parseObject(json.toString());
			}
			
		}
		
		return null;
	}
	
	public JSONArray getJSONArray(String key) {
		Object json = get(key);
		if(json!=null ) {
			if(json instanceof JSONArray) {
				return (JSONArray)json;
			}else if(json instanceof String){
				 return (JSONArray)JSON.parseArray((String)json);
			}else {
				return (JSONArray) JSON.toJSON(json);//Map ,List
				//return JSON.parseArray(json.toString());
			}
			
		}
		return null;
	}

	public static PageData toPageData(Object entity) {
		PageData pd = new PageData();
		if (entity != null) {
			pd.putAll(JSON.parseObject(JSONUtils.objectToJsonString(entity)));
		}
		return pd;
	}
	
	
	public PageData getPd(String key){
		return toPd(getJSONObject(key));
	}
	
	public List<PageData> getPdList(String key){
		return toPdList(getJSONArray(key));
	}
	
	public PageData toPd(JSONObject formData){
		if(formData==null || formData.isEmpty()) {
			return null;
		}
		PageData pdFormData = new PageData(formData);
		return pdFormData;
	}
	
	public  List<PageData>  toPdList(JSONArray formDataList){
		List<PageData> list = null;
		if(formDataList!=null && formDataList.size()>0) {
			list = new ArrayList<>();
			for (int i = 0; i < formDataList.size(); i++) {
				list.add(toPd(formDataList.getJSONObject(i)));
			}
		}
		return list;
	}

}
